/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.stylefeng.guns.modular.hp.controller;

import cn.stylefeng.guns.config.properties.HpProperties;
import cn.stylefeng.guns.core.common.annotion.BussinessLog;
import cn.stylefeng.guns.core.common.exception.BizExceptionEnum;
import cn.stylefeng.guns.core.common.node.ZTreeNode4Hp;
import cn.stylefeng.guns.core.log.LogObjectHolder;
import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.modular.hp.constant.MenuJumpTypeEnum;
import cn.stylefeng.guns.modular.hp.domain.MenuInfoDO;
import cn.stylefeng.guns.modular.hp.model.MenuInfo;
import cn.stylefeng.guns.modular.hp.model.PageContentInfo;
import cn.stylefeng.guns.modular.hp.service.IMenuInfoService;
import cn.stylefeng.guns.modular.hp.service.IPageContentInfoService;
import cn.stylefeng.guns.modular.hp.warpper.TopMenuInfoWrapper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.druid.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 首页栏目控制器
 *
 * @author xzqiang
 * @date 2018-12-08
 */
@Controller
@RequestMapping("/hp/menu")
public class MenuInfoController extends BaseController {

    private String PREFIX = "/hp/";
    
    @Autowired
    private HpProperties hpProperties;

    @Autowired
    private IMenuInfoService menuInfoService;
    
    @Autowired
    private IPageContentInfoService pageContentInfoService;

    /**
     * 跳转到首页栏目列表首页
     */
    @RequestMapping("/toindex/{type}")
    public String index(@PathVariable String type) {
    	String htmlPath = "";
    	switch (type) {
		case "top":
			htmlPath = "/topmenu/topmenu.html";
			break;
		case "left":
			htmlPath = "/leftmenu/leftmenu.html";
			break;
		default:
			break;
		}
    	
        return PREFIX + htmlPath;
    }

    /**
     * 跳转到添加首页栏目
     */
    @RequestMapping("/menu_add/{type}")
    public String topMenuAdd(@PathVariable String type) {
    	String htmlPath = "";
    	switch (type) {
		case "top":
			htmlPath = "/topmenu/topmenu_add.html";
			break;
		case "left":
			htmlPath = "/leftmenu/leftmenu_add.html";
			break;
		default:
			break;
		}
    	
        return PREFIX + htmlPath;
    }

    /**
     * 跳转到修改首页栏目
     */
    @RequestMapping("/menu_update/{type}/{topmenuId}")
    public String topMenuUpdate(@PathVariable String type,@PathVariable String topmenuId, Model model) {
    	MenuInfo menuInfo = this.menuInfoService.selectById(topmenuId);
    	
    	PageContentInfo pageContent = this.pageContentInfoService.selectById(menuInfo.getPageContentId());
    	
    	MenuInfoDO menuInfoDO = new MenuInfoDO();
    	menuInfoDO.setId(menuInfo.getId());
    	menuInfoDO.setType(menuInfo.getType());
    	menuInfoDO.setName(menuInfo.getName());
    	menuInfoDO.setContent(pageContent == null ? "" : pageContent.getContent());
    	menuInfoDO.setPri(menuInfo.getPri());
    	menuInfoDO.setDesc(menuInfo.getDesc());
        menuInfoDO.setCode(menuInfo.getCode());
        menuInfoDO.setJumpType(menuInfo.getJumpType());
        menuInfoDO.setParentid(menuInfo.getParentid());
        menuInfoDO.setLinkUrl(menuInfo.getLinkUrl());
        menuInfoDO.setSiteFlag(1);

        //如果父级是顶级菜单
        if(menuInfoDO.getParentid() == null || "0".equals(menuInfoDO.getParentid())){
            menuInfoDO.setParentid("0");
            menuInfoDO.setParentName("顶级");
        }else{
            MenuInfo parentMenuInfo = this.menuInfoService.selectById(menuInfoDO.getParentid());
            if(parentMenuInfo != null){
                menuInfoDO.setParentName(parentMenuInfo.getName());
            }else{
                menuInfoDO.setParentName("");
            }
        }
    	
        model.addAttribute("info", menuInfoDO);
        LogObjectHolder.me().set(menuInfo);

        String htmlPath = "";
    	switch (type) {
		case "top":
			htmlPath = "/topmenu/topmenu_edit.html";
			break;
		case "left":
			htmlPath = "/leftmenu/leftmenu_edit.html";
			break;
		default:
			break;
		}
    	
        return PREFIX + htmlPath;
    }

    /**
     * 跳转到首页通知
     */
    /*@RequestMapping("/hello")
    public String hello() {
        List<Map<String, Object>> notices = noticeService.list(null);
        super.setAttr("noticeList", notices);
        return "/blackboard.html";
    }*/

    /**
     * 获取首页栏目列表
     */
    @RequestMapping(value = "/list/{type}")
    @ResponseBody
    public Object list(@PathVariable String type,String condition) {
        List<Map<String, Object>> list = this.menuInfoService.list(type, condition);
        return super.warpObject(new TopMenuInfoWrapper(list));
    }

    /**
     * 新增首页栏目
     */
    @RequestMapping(value = "/add/{type}")
    @ResponseBody
    @BussinessLog(value = "新增首页栏目", key = "id")//, dict = NoticeMap.class
    public Object add(@PathVariable String type,MenuInfoDO topMenuInfoDO) {
        if (ToolUtil.isOneEmpty(topMenuInfoDO, topMenuInfoDO.getName(), topMenuInfoDO.getPri(), topMenuInfoDO.getContent()
                ,topMenuInfoDO.getCode(),topMenuInfoDO.getJumpType(),topMenuInfoDO.getParentid())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }

        //新增首页栏目信息
        MenuInfo MenuInfo = new MenuInfo();

        // 如果是详情页，则新增页面内容
        if(MenuJumpTypeEnum.DETAILS.equals(topMenuInfoDO.getJumpType())){
            //新增页面内容
            PageContentInfo pageContent = new PageContentInfo();
            pageContent.setContent(topMenuInfoDO.getContent());
            pageContent.setCreater(ShiroKit.getUser().getId());
            pageContent.setCreatedTime(new Date());
            pageContent.insert();
            MenuInfo.setPageContentId(pageContent.getId());
        }

        MenuInfo.setName(topMenuInfoDO.getName());
        MenuInfo.setType(type);
        MenuInfo.setPri(topMenuInfoDO.getPri());
        MenuInfo.setDesc(topMenuInfoDO.getDesc());
        MenuInfo.setSiteFlag(1);
        MenuInfo.setCode(topMenuInfoDO.getCode());
        MenuInfo.setJumpType(topMenuInfoDO.getJumpType());
        MenuInfo.setParentid(topMenuInfoDO.getParentid());

        //填补LinkUrl值
        String url = "";
        switch (topMenuInfoDO.getJumpType()){
            case MenuJumpTypeEnum.HOME:
                url = "#";
                break;
            case MenuJumpTypeEnum.DETAILS:
                url = MenuInfo.getPageContentId();
                break;
            case MenuJumpTypeEnum.LIST:
                url = MenuInfo.getCode();
                break;
            case MenuJumpTypeEnum.OTHERSITE:
                url = topMenuInfoDO.getLinkUrl() == null ? "" : topMenuInfoDO.getLinkUrl();
                break;
            case MenuJumpTypeEnum.LISTBTN:
                break;
            default:
                break;
        }
        MenuInfo.setLinkUrl(url);

        MenuInfo.setCreater(ShiroKit.getUser().getId());
        MenuInfo.setCreatedTime(new Date());
        MenuInfo.insert();
        return SUCCESS_TIP;
    }

    /**
     * 删除首页栏目
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @BussinessLog(value = "删除首页栏目", key = "id")//, dict = NoticeMap.class
    public Object delete(@RequestParam String id) {

        this.menuInfoService.deleteById(id);

        return SUCCESS_TIP;
    }

    /**
     * 修改首页栏目
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    @BussinessLog(value = "修改首页栏目")//, dict = NoticeMap.class
    public Object update(MenuInfoDO topMenuInfoDO) {
    	if (ToolUtil.isOneEmpty(topMenuInfoDO, topMenuInfoDO.getName(), topMenuInfoDO.getPri(), topMenuInfoDO.getContent()
                                ,topMenuInfoDO.getCode(),topMenuInfoDO.getJumpType(),topMenuInfoDO.getParentid())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
    	MenuInfo oldTopMenuInfo = this.menuInfoService.selectById(topMenuInfoDO.getId());
        PageContentInfo oldPageContent = null;
        // 如果是详情页，则更新页面内容
        if(MenuJumpTypeEnum.DETAILS.equals(topMenuInfoDO.getJumpType())){
            //判断之前是否存在页面ID,有则更新，无则新建
            if(!StringUtils.isEmpty(oldTopMenuInfo.getPageContentId())){
                oldPageContent = this.pageContentInfoService.selectById(oldTopMenuInfo.getPageContentId());
                oldPageContent.setContent(topMenuInfoDO.getContent());
                oldPageContent.updateById();
            }else{
                oldPageContent = new PageContentInfo();
                oldPageContent.setContent(topMenuInfoDO.getContent());
                oldPageContent.setCreater(ShiroKit.getUser().getId());
                oldPageContent.setCreatedTime(new Date());
                oldPageContent.insert();
            }
        }

    	oldTopMenuInfo.setName(topMenuInfoDO.getName());
    	oldTopMenuInfo.setPri(topMenuInfoDO.getPri());
    	oldTopMenuInfo.setDesc(topMenuInfoDO.getDesc());

        oldTopMenuInfo.setCode(topMenuInfoDO.getCode());
        oldTopMenuInfo.setJumpType(topMenuInfoDO.getJumpType());
        oldTopMenuInfo.setParentid(topMenuInfoDO.getParentid());
        oldTopMenuInfo.setSiteFlag(1);

        //填补LinkUrl值
        String url = "";
        switch (topMenuInfoDO.getJumpType()){
            case MenuJumpTypeEnum.HOME:
                url = "#";
                break;
            case MenuJumpTypeEnum.DETAILS:
                url = oldPageContent.getId();
                break;
            case MenuJumpTypeEnum.LIST:
                url = oldTopMenuInfo.getCode();
                break;
            case MenuJumpTypeEnum.OTHERSITE:
                url = topMenuInfoDO.getLinkUrl() == null ? "" : topMenuInfoDO.getLinkUrl();
                break;
            case MenuJumpTypeEnum.LISTBTN:
                break;
            default:
                break;
        }
        oldTopMenuInfo.setLinkUrl(url);


        //填补LinkUrl值
        if(topMenuInfoDO.getUpdateUrlFlag() != null && topMenuInfoDO.getUpdateUrlFlag() == 1){
            oldTopMenuInfo.setLinkUrl(topMenuInfoDO.getLinkUrl());
        }

        if(oldTopMenuInfo.getType().equals("left")){
            if(MenuJumpTypeEnum.OTHERSITE.equals(topMenuInfoDO.getJumpType())){
                oldTopMenuInfo.setLinkUrl(topMenuInfoDO.getLinkUrl());
            }else if(MenuJumpTypeEnum.DETAILS.equals(topMenuInfoDO.getJumpType())){
                oldTopMenuInfo.setLinkUrl(oldPageContent.getId());
            }else if(MenuJumpTypeEnum.LIST.equals(topMenuInfoDO.getJumpType())){
                oldTopMenuInfo.setLinkUrl(oldTopMenuInfo.getCode());
            }
        }

    	oldTopMenuInfo.updateById();
        return SUCCESS_TIP;
    }



    /**
     * 获取菜单列表(选择父级菜单用)
     */
    @RequestMapping(value = "/selectMenuTreeList")
    @ResponseBody
    public List<ZTreeNode4Hp> selectMenuTreeList() {
        List<ZTreeNode4Hp> roleTreeList = this.menuInfoService.menuTreeList();
        roleTreeList.add(ZTreeNode4Hp.createParent());
        return roleTreeList;
    }
}
